package uscdb.service.impl;

import java.util.ArrayList;
import java.util.HashMap;
import java.util.List;
import java.util.Map;
import java.util.UUID;

import org.springframework.beans.BeanUtils;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;

import uscdb.dao.MissionDaoI;
import uscdb.model.Tmission;
import uscdb.pageModel.DataGrid;
import uscdb.pageModel.Json;
import uscdb.pageModel.Mission;
import uscdb.pageModel.PageHelper;
import uscdb.service.MissionServiceI;

@Service
public class MissionServiceImpl implements MissionServiceI {

	@Autowired
	private MissionDaoI misssionDao;

	@Override
	public void add(Mission mission) {
		mission.setId(UUID.randomUUID().toString());
		Tmission tmission = new Tmission();
		BeanUtils.copyProperties(mission, tmission);
		misssionDao.save(tmission);
	}

	@Override
	public void edit(Mission mission) {
		Tmission tmission = misssionDao.get(Tmission.class, mission.getId());
		if (null != tmission) {
			BeanUtils.copyProperties(mission, tmission, new String[] { "id" });
		}

	}

	@Override
	public Json delete(String ids) {
		Json json = new Json();
		for (String id : ids.split(",")) {
			Tmission tmission = misssionDao.get(Tmission.class, id);
			misssionDao.delete(tmission);
		}
		json.setMsg("删除成功");
		json.setSuccess(true);
		return json;

	}

	@Override
	public DataGrid dataGrid(Mission mission, PageHelper ph) {
		DataGrid dg = new DataGrid();
		List<Mission> missionList = new ArrayList<>();
		Map<String, Object> params = new HashMap<>();
		String hql = "from Tmission t ";
		List<Tmission> tmissionList = misssionDao.find(hql + whereHql(mission, params) + orderHql(ph), params,
				ph.getPage(), ph.getRows());
		for (Tmission tmission : tmissionList) {
			Mission mission2Page = new Mission();
			BeanUtils.copyProperties(tmission, mission2Page);
			missionList.add(mission2Page);
		}
		dg.setRows(missionList);
		dg.setTotal(misssionDao.count("select count(*) " + hql + whereHql(mission, params), params));
		return dg;
	}

	/**
	 * 排序函数
	 * 
	 * @param ph
	 *            分页对象
	 * @return
	 */
	private String orderHql(PageHelper ph) {
		String orderString = "";
		if (ph.getSort() != null && ph.getOrder() != null) {
			orderString = " order by t." + ph.getSort() + " " + ph.getOrder();
		}
		return orderString;
	}

	private String whereHql(Mission mission, Map<String, Object> params) {
		String hql = "";
		if (null != mission) {
			hql += " where 1=1 ";
		}
		return hql;
	}

}
